Convert Binary Number to Octal and vice-versa using C++

04-11-17 Course- CPP

This program converts either binary number entered by user to octal number or octal number entered by user to binary number in accordance with the character entered by user.

Source Code to Convert Binary to Octal and Vice Versa


/* C++ programming source code to convert either binary to octal or octal to binary according to data entered by user. */

#include <iostream>
#include <cmath>
using namespace std;
int binary_octal(int n);
int octal_binary(int n);
int main()
{
   int n;
   char c;
   cout << "Instructions: " << endl;
   cout << "1. Enter alphabet 'o' to convert binary to octal." << endl;
   cout << "2. Enter alphabet 'b' to convert octal to binary." << endl;
   cin >> c;
   if (c =='b' || c == 'B')
   {
       cout << "Enter a octal number: ";
       cin >> n;
       cout << n << " in octal = " << octal_binary(n) << " in binary";
   }
   if (c =='o' || c == 'O')
   {
       cout << "Enter a binary number: ";
       cin >> n;
       cout << n << " in binary = " << binary_octal(n) << " in octal";
   }
   return 0;
}
int binary_octal(int n)  /* Function to convert binary to octal. */
{
    int octal=0, decimal=0, i=0;
    while(n!=0)
    {
        decimal+=(n%10)*pow(2,i);
        ++i;
        n/=10;
    }

/*At this point, the decimal variable contains corresponding decimal value of binary number. */

    i=1;
    while (decimal!=0)
    {
        octal+=(decimal%8)*i;
        decimal/=8;
        i*=10;
    }
    return octal;
}
int octal_binary(int n)  /* Function to convert octal to binary.*/
{
    int decimal=0, binary=0, i=0;
    while (n!=0)
    {
        decimal+=(n%10)*pow(8,i);
        ++i;
        n/=10;
    }

/* At this point, the decimal variable contains corresponding decimal value of that octal number. */

    i=1;
    while(decimal!=0)
    {
        binary+=(decimal%2)*i;
        decimal/=2;
        i*=10;
    }
    return binary;
}

Output


Instructions:
1. Enter alphabet 'o' to convert binary to octal.
2. Enter alphabet 'b' convert octal to binary.
o
Enter a binary number: 11011
11011 in binary = 33 in octal

This program asks user to enter alphabet 'b' to convert octal number to binary or alphabet 'o' to convert binary number to octal. In accordance with the character entered, user is asked to enter either binary value to convert to octal or octal value to convert to binary.

To perform conversion, two functions are made octal_binary(); to convert octal to binary and binary_octal(); to convert binary to octal. Octal number entered by user is passed to octal_binary() and this function computes the binary value of that octal number number and returns it main() function. Similarly, binary number is passed to function binary_octal() and this function computes octal value of that number and return it main() function.